const pageHelper = require('../../../../helpers/page_helper');
const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { plmStatisticsStore } = require('../../../../store/modules/statistics_store');
const { projectContext } = require('../../../../helpers/project_context');
const Day = require('dayjs');
const { logEvent } = require('../../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../../helpers/network_helper.js');

Page({
  data: {
    projectId: '',
    projectType: '',
    
    // 周期选择
    periodOptions: [
      { text: '本周', value: 'week' },
      { text: '本月', value: 'month' },
      { text: '本季度', value: 'quarter' },
      { text: '本年', value: 'year' },
      { text: '自定义', value: 'custom' }
    ],
    selectedPeriod: 'week',
    showDatePicker: false,
    
    // 图表数据
    progressChartData: {},
    timelineChartData: {},
    milestoneChartData: {},
    
    // 折叠面板
    activeCollapse: ['1', '2', '3'],
    
    // 是否显示导出按钮
    canExport: false
  },
  
  onLoad: async function(options) {
    // 网络检测
    const net = await getNetworkStatus();
    if (!net.isConnected) {
      wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
    } else if (net.networkType === '2g') {
      wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
    }
    listenNetworkStatus((res) => {
      if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
      else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
    });
    logEvent('page_load', { page: 'plm_statistics_progress' });
    
    // 创建MobX绑定
    this.storeBindings = createStoreBindings(this, {
      store: plmStatisticsStore,
      fields: ['loading', 'error', 'progressStatistics', 'period', 'dateRange'],
      actions: ['getProjectProgress', 'setPeriod', 'setDateRange']
    });
    
    if (options.id) {
      // 设置项目ID
      this.setData({ 
        projectId: options.id,
        projectType: options.model || '项目进度'
      });
      
      // 初始加载数据
      this.loadProgressData(options.id);
    } else {
      // 尝试从上下文获取当前项目
      const currentProject = projectContext.getCurrentProjectInfo();
      if (currentProject) {
        this.setData({
          projectId: currentProject._id,
          projectType: currentProject.model || '项目进度'
        });
        
        // 初始加载数据
        this.loadProgressData(currentProject._id);
      } else {
        pageHelper.showErrorToast('未找到项目信息');
        setTimeout(() => wx.navigateBack(), 1500);
      }
    }
    
    // 检查用户权限
    this._checkUserPermission();
  },
  
  // 加载进度数据
  loadProgressData: function(projectId) {
    this.getProjectProgress(projectId).then(() => {
      if (this.data.progressStatistics) {
        // 准备图表数据
        this._prepareChartData();
      }
    }).catch(err => {
      pageHelper.showErrorToast('加载数据失败：' + err.message);
    });
  },
  
  // 准备图表数据
  _prepareChartData: function() {
    if (!this.data.progressStatistics) return;
    
    const statistics = this.data.progressStatistics;
    
    // 进度对比图表数据
    this.setData({
      progressChartData: {
        series: [
          { name: '计划进度', value: statistics.progress.plannedProgress },
          { name: '实际进度', value: statistics.progress.overall }
        ]
      }
    });
    
    // 进度时间线图表数据
    if (statistics.progress.timeline && statistics.progress.timeline.length > 0) {
      const timeline = statistics.progress.timeline;
      this.setData({
        timelineChartData: {
          xAxis: timeline.map(item => Day(item.date).format('MM-DD')),
          series: [
            {
              name: '计划进度',
              data: timeline.map(item => item.planned)
            },
            {
              name: '实际进度',
              data: timeline.map(item => item.actual)
            }
          ]
        }
      });
    }
    
    // 里程碑完成情况
    if (statistics.progress.milestones && statistics.progress.milestones.length > 0) {
      const milestones = statistics.progress.milestones;
      
      // 分类统计已完成和未完成
      const completed = milestones.filter(m => m.completed).length;
      const uncompleted = milestones.length - completed;
      
      this.setData({
        milestoneChartData: {
          series: [
            { name: '已完成', value: completed },
            { name: '未完成', value: uncompleted }
          ]
        }
      });
    }
  },
  
  // 切换周期
  onPeriodChange: function(e) {
    const period = e.currentTarget.dataset.value;
    this.setData({ selectedPeriod: period });
    
    // 切换显示自定义日期选择器
    if (period === 'custom') {
      this.setData({ showDatePicker: true });
      return;
    } else {
      this.setData({ showDatePicker: false });
    }
    
    // 设置周期并刷新数据
    this.setPeriod(period);
    this.loadProgressData(this.data.projectId);
  },
  
  // 日期范围变更
  onDateRangeChange: function(e) {
    const { start, end } = e.detail;
    
    // 设置日期范围并刷新数据
    this.setDateRange(start, end);
    this.loadProgressData(this.data.projectId);
  },
  
  // 刷新图表数据
  onChartRefresh: function() {
    this.loadProgressData(this.data.projectId);
  },
  
  // 折叠面板状态变更
  onCollapseChange: function(e) {
    this.setData({
      activeCollapse: e.detail
    });
  },
  
  // 导出报告
  exportReport: function() {
    // 显示导出选项
    wx.showActionSheet({
      itemList: ['导出为Excel', '导出为PDF', '生成周报'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 导出Excel
          this._exportExcel();
        } else if (res.tapIndex === 1) {
          // 导出PDF
          this._exportPDF();
        } else if (res.tapIndex === 2) {
          // 生成周报
          this._generateWeeklyReport();
        }
      }
    });
  },
  
  // 导出Excel
  _exportExcel: function() {
    wx.showLoading({ title: '正在导出...' });
    
    // 调用云函数导出Excel
    wx.cloud.callFunction({
      name: 'exportStatistics',
      data: {
        type: 'excel',
        projectId: this.data.projectId,
        module: 'progress',
        period: this.data.period,
        dateRange: this.data.dateRange
      }
    }).then(res => {
      wx.hideLoading();
      
      if (res.result && res.result.fileID) {
        // 下载文件
        wx.cloud.downloadFile({
          fileID: res.result.fileID,
          success: result => {
            // 保存文件到本地
            wx.saveFile({
              tempFilePath: result.tempFilePath,
              success: saveRes => {
                wx.openDocument({
                  filePath: saveRes.savedFilePath,
                  showMenu: true
                });
              },
              fail: err => {
                pageHelper.showErrorToast('保存文件失败');
              }
            });
          },
          fail: err => {
            pageHelper.showErrorToast('下载文件失败');
          }
        });
      } else {
        pageHelper.showErrorToast('导出失败');
      }
    }).catch(err => {
      wx.hideLoading();
      pageHelper.showErrorToast('导出失败：' + err.message);
    });
  },
  
  // 导出PDF
  _exportPDF: function() {
    pageHelper.showSuccessToast('PDF导出功能开发中');
  },
  
  // 生成周报
  _generateWeeklyReport: function() {
    pageHelper.showSuccessToast('周报生成功能开发中');
  },
  
  // 检查用户权限
  _checkUserPermission: function() {
    // 从全局用户权限检查（实际实现可能不同）
    const app = getApp();
    const userInfo = app.globalData.userInfo || {};
    const userPermissions = userInfo.permissions || {};
    
    // 检查是否有导出权限
    const canExport = userPermissions.project?.admin === true || 
                      userPermissions.statistics?.export === true;
    
    this.setData({ canExport });
  },
  
  onPullDownRefresh: function() {
    // 下拉刷新
    this.loadProgressData(this.data.projectId).then(() => {
      wx.stopPullDownRefresh();
    }).catch(() => {
      wx.stopPullDownRefresh();
    });
  },
  
  onShareAppMessage: function() {
    return {
      title: `${this.data.project.model}进度统计`,
      path: `/projects/plm/pages/project/statistics/progress/progress?id=${this.data.project._id}&model=${this.data.project.model}`
    };
  },
  
  onUnload: function() {
    // 销毁MobX绑定
    this.storeBindings.destroyStoreBindings();
  }
}); 